package com.sendpo.zjx.sendpo.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableRecyclerView;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.JobDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.services.AmapLocationService;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/8/14.
 */

public class ZhaoPinListActivity extends AppCompatActivity implements AMapLocationListener{


    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.city)
    TextView city;
    @BindView(R.id.head)
    RelativeLayout head;
    private RecylcerAdaper adpater;
    @BindView(R.id.recyclerview)
    PullableRecyclerView recyclerview;
    @BindView(R.id.pulltofresh)
    public PullToRefreshLayout pulltofresh;
    private LinearLayoutManager lm;
    private RecylcerAdaper adpter;
    private int pagenow = 1;
    private int pagesize = 10;
    private AmapLocationService amapLocationService;
    private  String companyCity="";
    private  String companyArea="";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhaopinlist);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();
    }

    private void initComponent() {
        lm = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false);
        recyclerview.setLayoutManager(lm);
        List<JobDomain.DataBean> dataBeanList = new ArrayList<>();
        recyclerview.setAdapter(adpter = new RecylcerAdaper(dataBeanList, this));
        pulltofresh.setPullDownEnable(true);
        pulltofresh.setPullUpEnable(true);
        pulltofresh.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                amapLocationService = new AmapLocationService(ZhaoPinListActivity.this);
                amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
                amapLocationService.registerListener(ZhaoPinListActivity.this);
                amapLocationService.start();

            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                pagenow++;
                append(pagenow);
            }
        });

        pulltofresh.autoRefresh();


    }

    public AMapLocationClientOption getDefaultAmapLocationOptions() {
        AMapLocationClientOption mLocationOption = null;
        if (mLocationOption == null) {
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
            mLocationOption.setLocationCacheEnable(true);
            mLocationOption.setOnceLocation(true);
            mLocationOption.setOnceLocationLatest(false);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否强制刷新WIFI，默认为true，强制刷新。
            mLocationOption.setWifiScan(true);
            mLocationOption.setInterval(1000);
            //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(20000);
        }
        return mLocationOption;
    }
    @OnClick(value = R.id.backbt)
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;

        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
           if(aMapLocation==null){
               pulltofresh.refreshFinish(PullToRefreshLayout.SUCCEED);
               return;
           }

        companyCity=aMapLocation.getCity();
        city.setText(""+companyCity);
        companyArea=aMapLocation.getDistrict();
        pagenow = 1;
        query(pagenow);
    }

    public class RecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<JobDomain.DataBean> dataBeen;
        public LayoutInflater inflater;

        public RecylcerAdaper(List<JobDomain.DataBean> dataBeen, Context context) {
            inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder ih = null;
            ih = new IndexHoler(inflater.inflate(R.layout.layout_zhaopinlist_listitem, parent, false));
            return ih;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            IndexHoler ih = (IndexHoler) holder;
            final JobDomain.DataBean dataBean = dataBeen.get(position);

            ih.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("data", dataBean);
                    map.put("type", 0);
                    Tools.redirectActivity(ZhaoPinListActivity.this, ZhaoPinInfoActivity.class, map);
                }
            });

            ih.name.setText("" + dataBean.getJobName());
            ih.money.setText("" + dataBean.getJobSalary() + "元/月");
            ih.address.setText("" + dataBean.getCompanyAddress());
            ih.citydistinct.setText("" + dataBean.getCompanyCity() + dataBean.getCompanyArea());
            ih.jobreigster_tv.setText(""+dataBean.getJobregister_num()+"人应聘");
        }

        @Override
        public int getItemCount() {
            return dataBeen.size();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public View rootView;
            public RelativeLayout myself_master;
            public Button userinfo;
            public TextView name;
            public TextView money;
            public TextView citydistinct;
            public TextView address;
              public TextView jobreigster_tv;

            public IndexHoler(View itemView) {
                super(itemView);
                address = itemView.findViewById(R.id.address);
                citydistinct = itemView.findViewById(R.id.citydistinct);
                rootView = itemView.findViewById(R.id.rootview);
                myself_master = itemView.findViewById(R.id.myself_master_controll_ll);
                userinfo = itemView.findViewById(R.id.userinfo);
                name = itemView.findViewById(R.id.name);
                money = itemView.findViewById(R.id.money);
                jobreigster_tv=itemView.findViewById(R.id.jobreigster_tv);

            }

        }

        public void deleteRow(int position) {
            dataBeen.remove(position);
            notifyDataSetChanged();
        }

        public void initRefresh(List<JobDomain.DataBean> domains) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void initAppend(List<JobDomain.DataBean> domains) {
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void delete(int position) {
            this.dataBeen.remove(position);
            notifyDataSetChanged();
        }

    }


    public void query(int pagenow) {
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("companyCity", companyCity + "");
        map.put("companyArea", companyArea + "");

        Xutils.POST(HttpUrl.jobmerchantsbylocationquery, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                pulltofresh.refreshFinish(PullToRefreshLayout.SUCCEED);
                Gson gson = new Gson();
                JobDomain domain = gson.fromJson(result, JobDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(), ZhaoPinListActivity.this));
                            } else {
                                adpter.initRefresh(domain.getData());
                            }

                        } else {

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pulltofresh.refreshFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void append(int pagenow) {

        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("companyCity", companyCity + "");
        map.put("companyArea", companyArea + "");
        Xutils.POST(HttpUrl.jobmerchantsbylocationquery, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                Gson gson = new Gson();
                JobDomain domain = gson.fromJson(result, JobDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(), ZhaoPinListActivity.this));
                            } else {
                                adpter.initAppend(domain.getData());
                            }
                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                pulltofresh.loadmoreFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

}
